//
//  sumitup2ViewController.m
//  sumitup2
//
//  Created by Maelyss FARGES on 28/10/2011.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "sumitup2ViewController.h"


@implementation sumitup2ViewController

@synthesize label_score;
@synthesize label_time;
@synthesize label_target;
@synthesize label_status;
//@synthesize label_currentSelection2;
@synthesize label_result;

//create a new dynamic button
- (void)addButton {
	
	button[button_count] = [UIButton buttonWithType:UIButtonTypeCustom];
	CGRect frame = CGRectMake(45 + arc4random()%220,140 + arc4random()%230, 50, 60);
	
	button[button_count].frame = frame;
	button[button_count].tag=button_count;
	
	//int fromNumber = 10;
	//int toNumber = 30;

	int randomNumber = (arc4random()%(toNumber-fromNumber))+fromNumber;
	
	[button[button_count] setTitle:(NSString *)[NSString stringWithFormat:@"%d",randomNumber] forState:(UIControlState)UIControlStateNormal];
	[button[button_count] addTarget:self action:@selector(addCurrentSelection:) forControlEvents:UIControlEventTouchUpInside];
	[button[button_count] setBackgroundImage:[UIImage imageNamed:@"baloun.png"] forState:UIControlStateNormal];
	[self.view addSubview:button[button_count]];
	
	button[button_count].alpha = 0.5;
	[button[button_count] setTitleColor:[UIColor greenColor] forState:UIControlStateNormal];
	button_count++;
	
}

- (IBAction)addCurrentSelection:(id)sender {
	if (endGame == FALSE)
	{
	
	
	// take text
	UIButton *button_selected = button[((UIButton *)sender).tag];
	BOOL Succeed;
	if (finish == TRUE)
	{
		label_result.text = @"";
		finish = FALSE;
	}
	if (label_result.text == @"")
	{
		label_result.text = button_selected.currentTitle;
		//label_result.text = [NSString stringWithFormat:@"%ld + ?",label_result.text];
	}
	else
	{
		//if ([label_currentSelection2.text integerValue] == 0)
		//{
			finish = TRUE;
			//label_currentSelection2.text = button_selected.currentTitle;
			int result = [label_result.text integerValue] + [button_selected.currentTitle integerValue];
			//NSString *bob = [NSString stringWithFormat:@"%d",result];
			//label_result.text = bob;
			
			if (result == [label_target.text integerValue])
			{
				Succeed = TRUE;

				toNumber += 2;
				
				
				button_answer[0] = 404;
				button_answer[1] = 404;
				
				score = score + 100*button_count/2;
				label_score.text = [NSString stringWithFormat:@"%d",score];
				countdown += 5;
				label_time.text = [NSString stringWithFormat:@"%d",countdown];
				
				label_result.text = @"TRUE";
				label_result.textColor = [UIColor greenColor];
			}
			else 
			{
				score = score - 50;
				label_score.text = [NSString stringWithFormat:@"%d",score];
				
				countdown -= 3;
				label_time.text = [NSString stringWithFormat:@"%d",countdown];
				
				label_result.text = [NSString stringWithFormat:@"FALSE = %d",result];
				label_result.textColor = [UIColor redColor];
			}
		}

	
	[self newButton:button_selected];
	
	if (Succeed == TRUE)
	{
		[self newTarget];
	}
	}
	else {
		[self newGame];
	}
}

- (void)newGame
{
	endGame = TRUE;
	[self viewDidLoad];
}

- (void)newButton:(UIButton *)button_selected 
{
	if (endGame == FALSE)
	{
	
	button_selected.center = CGPointMake(45 + arc4random()%220,370);
	if (button_selected.tag != button_answer[0] && button_selected.tag != button_answer[1])
	{
			int randomNumber = (arc4random()%(toNumber-fromNumber))+fromNumber;
		[button_selected setTitle:(NSString *)[NSString stringWithFormat:@"%d",randomNumber] forState:(UIControlState)UIControlStateNormal];
	}
	}
	else {
		[self printScore];
	}

}

- (void)newTarget {
	// Select new Target
	do {
		button_answer[0] = arc4random() % button_count;
		button_answer[1] = arc4random() % button_count;
	} while (button_answer[0] == button_answer[1]);
	
	int newAnswer = [button[button_answer[0]].currentTitle integerValue] + [button[button_answer[1]].currentTitle integerValue];
	
	label_target.text = [NSString stringWithFormat:@"%d",newAnswer];
	// END Selet new Target

}

-(IBAction)goMainMenu
{
	[countdownTimer invalidate];
	
	mainMenu *picker = [
						[mainMenu alloc]
						initWithNibName:@"mainMenu" bundle:nil];
	picker.slave = self;
	[self presentModalViewController:picker animated:YES];
	[picker release];
}



/*
// The designated initializer. Override to perform setup that is required before the view is loaded.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {

    }
    return self;
}
*/

/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
}
*/



// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
	
	
	fromNumber = 1;
	toNumber = 10;
	score = 0;
	
	label_status.text = @"HIT THE TARGET";
	//label_currentSelection2.text = @"0";
	//label_target.text = [NSString stringWithFormat:@"%d",(arc4random() % 10)+1];
	label_result.text = @"TRUE";
	label_time.text = @"60";
	label_score.text = @"score";
	label_result.textColor = [UIColor greenColor];
	
	for (int i=0; i<button_count; i++) {
		button[i].center = CGPointMake(1000,10000);
	}
	button_count = 0;
	for (int i=0; i<6; i++) {
		[self addButton];
		
	}
	[self newTarget];
	
	if (!endGame)
	{
		[self startCountdown];
	}
	
	countup = 0;
	countdown = 60;
	turn = 0;
	turn_velocity = -1.7;
	turn_check = TRUE;
	endGame = FALSE;

}

- (void)startCountdown
{
	countdownTimer = [NSTimer scheduledTimerWithTimeInterval:0.05 target:self     selector:@selector(advanceTimer:) userInfo:nil repeats:YES];
    NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
    [runLoop addTimer:countdownTimer forMode:NSDefaultRunLoopMode];
}











// TODO




/*



- (void)moveButton:(UIButton *)button_moving
{
	//UIButton *button_moving = (UIButton *)sender;
	/*
	button_moving.center = CGPointMake(45 + arc4random()%220,325);
	button_moving.alpha = 1.;
	
	[UIView animateWithDuration:20
						  delay:0
						options:UIViewAnimationOptionAllowUserInteraction
					 animations:^{button_moving.center = CGPointMake(45 + arc4random()%220,140); }
						 
					 completion:^(BOOL finished){  }];
	
	/*[UIView animateWithDuration:20
                          delay:0
                        options:UIViewAnimationOptionAllowUserInteraction
                     animations:^{
                         [button_moving setAlpha:0.0];
                     }
                     completion:nil];*/
	/*
	UIViewAnimationOptions options = UIViewAnimationOptionCurveLinear | UIViewAnimationOptionAllowUserInteraction;
	
	[UIView animateWithDuration:20.0 delay:0.0 options:options animations:^
	{
		button_moving.center = CGPointMake(45 + arc4random()%220,140);
	} completion:nil];
	
	if (!highlightView) {
		UIImageView *tempImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Highlight"]];
		self.highlightView = tempImageView;
		[tempImageView release];
		
		[self addSubview:highlightView];
	}
	
	highlightView.alpha = 0.0;
	
	[UIView beginAnimations:nil context:nil];
	[UIView setAnimationDuration:0.5];
	button_moving.center = CGPointMake(45 + arc4random()%220,140);
	[UIView commitAnimations];
	 
}
*/
	 
- (void)printScore
{
	button[0].center = CGPointMake(160, 429);
	[button[0] setTitle:(NSString *)[NSString stringWithFormat:@"%d",score] forState:(UIControlState)UIControlStateNormal];
}

- (void)advanceTimer:(NSTimer *)timer
{
	
	countup++;
	if (countup==25)
	{
		
		countup=0;
		if (endGame == FALSE)
		{
			countdown--;
		
			if (countdown <= 0)
			{
				// code to stop the timer
				countdown = -10;	
				label_status.text = @"GAME OVER";
				label_target.text = @"balloon score !";
				label_result.text = @"click to restart";
			
				for (int i=0; i<button_count; i++) {
					button[i].center = CGPointMake(1000,10000);
				}
				button_count = 1;
			
				[self printScore];

				
				
				/*
				 NSString *filePath = [[NSBundle mainBundle]
				 pathForResource:@"highscore" ofType:@"plist"];
				 NSArray *filedata = [[NSArray alloc] initWithContentsOfFile:filePath];

			    NSArray *mydata = filedata;
				filedata.
				[filedata release];
				*/
				
			
				endGame = TRUE;
			}
		}
		label_time.text = [NSString stringWithFormat:@"%d",countdown];
		turn_check = !turn_check;

	}
	
		
	
	
	
	if (turn_check)
	{
		turn_velocity += 0.15;
	}
	else {
		turn_velocity -= 0.15;
	}

	turn = turn_velocity;
		for (int i=0; i<button_count; i++) {
			button[i].center = CGPointMake((button[i].frame.origin.x+25)+turn, (button[i].frame.origin.y+30)-1);
			if (button[i].frame.origin.y+20 < 140) {
				[self newButton:button[i]];
			}
		}
	


}


/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}


- (void)dealloc {
    [super dealloc];
}

@end
